<?php
include($_SERVER["DOCUMENT_ROOT"] . "/bob.php");
include("fonctions_forum.php");
require ($_SERVER["DOCUMENT_ROOT"] . "/lib/simple_html_dom.php");
$mysqli = new_mysqli($host, $user, $password, $database); //connection à la DB

$variable_post = filter_input_array(INPUT_POST);
$variable_get = filter_input_array(INPUT_GET);

$motscle = "";
$cherche_forum = 0;
$type_recherche = 'topics';
$champ_recherche = 'topic_title';
$variable_order = 'topic_time';
$order = "ASC";
$nb_message=0;
$get = "";
if ($variable_post['btn_recherche']) {
    $motscle = get_data_ss_tag($variable_post['motscles']);
    if ($motscle != "") {
        $get = "motscle=" . urlencode($motscle);
    }
    $cherche_forum = $variable_post['select_forum'];
    $get.= "&forum=" . $cherche_forum;
    $type_recherche = $variable_post['dans'];
    $get.= "&dans=" . $type_recherche;
    switch ($type_recherche) {
        case 'topics':
            $variable_order = 'topic_time';
            $champ_recherche = 'topic_title';
            break;
        case 'posts':
            $variable_order = 'post_time';
            $champ_recherche = 'post_text';
            break;
    }

    $order = $variable_post['ordre'];
    $get.= "&order=" . $order;
}elseif (isset($variable_post['recherche'])) {
    $motscle = get_data_ss_tag($variable_post['recherche']);
    if ($motscle != "") {
        $get = "motscle=" . urlencode($motscle);
    }
    $get="&forum=0&dans=topics&order=ASC";
}else{
    if(isset($variable_get['motscle'])){
        $motscle=  urldecode($variable_get['motscle']);
        $get = "motscle=" . $variable_get['motscle'];
        
        $cherche_forum=$variable_get['forum'];
        $get.= "&forum=" . $cherche_forum;
        $type_recherche = $variable_get['dans'];
        $get.= "&dans=" . $type_recherche;
        switch ($type_recherche) {
        case 'topics':
            $variable_order = 'topic_time';
            $champ_recherche = 'topic_title';
            break;
        case 'posts':
            $variable_order = 'post_time';
            $champ_recherche = 'post_text';
            break;
        }
        $order = $variable_get['order'];
        $get.= "&order=" . $order;
    }
        
}

//construction requète
$result = array();
$from = "";
$feedback = "";
if ($motscle != "") {
    $tmots = explode(" ", $motscle);
    $rech = "";
    for ($i = 0; $i < sizeof($tmots); $i++) {
        if ($i > 0)
            $rech = $rech . " AND LOWER(" . $champ_recherche . ") LIKE LOWER('%" . $mysqli->real_escape_string($tmots[$i]) . "%')";
        else
            $rech = $rech . " LOWER(" . $champ_recherche . ") LIKE LOWER('%" . $mysqli->real_escape_string($tmots[$i]) . "%')";
    }
    if ($cherche_forum > 0) {
        $rech.=" AND forum_id=" . $cherche_forum;
    }
    $from = "FROM forum_" . $type_recherche . " WHERE " . $rech . " ORDER BY " . $variable_order . " " . $order;
    $nb_resultat = mysqli_query_with_error($mysqli, "SELECT COUNT(*) as nb " . $from)->fetch_assoc();
    $nb_message = get_num($nb_resultat['nb']);
    switch ($nb_message) {
        case 0 :
            $feedback = "Il n'y a aucun résultat correspondant à votre recherche.";
            break;
        default:
            $feedback = $nb_message . " résultat" . (($nb_message > 1) ? 's' : '') . " correspondent à votre recherche.";
    }
    //Pagination - Initialisation

    if (isset($variable_get['page'])) {
        $page = $variable_get['page'];
    } else {
        $page = 1;
    }
    $nb_message_par_page = 10;

    $total = $nb_message;
    $nombreDePages = ceil($total / $nb_message_par_page);
    $pageActuelle = intval($page);
    if ($pageActuelle > $nombreDePages) {
        $pageActuelle = $nombreDePages;
    }
    $premiereEntree = ($pageActuelle - 1) * $nb_message_par_page;

    $limit = "LIMIT " . $premiereEntree . "," . $nb_message_par_page;

    //$result = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE $rech ORDER BY post_id DESC");
} else {
    $feedback = "Veuillez saisir un ou plusieurs mots-clés.";
}



entete($mysqli, "Recherche",";recherche");
?>
<h4 class='ombre'>Résultat de la recherche</h4>
<div class="ombre clear">
    <form id="recherche_avancee" method="post" action="recherche.php">

        <h5>Recherche avancée</h5>
        <div class="col_g">
            <label for="motscles">Mots-clés</label>
            <input type="text" name="motscles" id="motscles" value="<?php echo $motscle ?>" maxlength="80" class="texte">

            <div class="tri">
                <p class="label">Rechercher dans</p>
                <input type="radio" name="dans" value="topics" id="titre_msg" class="input_reponse" <?php echo (($type_recherche == "topics") ? 'CHECKED' : ''); ?>>
                <label for="titre_msg">le titre des sujets</label>
                <input type="radio" name="dans" value="posts" id="corps_msg" class="input_reponse" <?php echo (($type_recherche == "posts") ? 'CHECKED' : ''); ?>>
                <label for="corps_msg">le corps des messages</label><br/>

                <p class="label">Par ordre chronologique</p>
                <input type="radio" name="ordre" value="ASC" id="croissant" class="input_reponse" <?php echo (($order == "ASC") ? 'CHECKED' : ''); ?>>
                <label for="croissant">croissant</label>
                <input type="radio" name="ordre" value="DESC" id="decroissant" class="input_reponse" <?php echo (($order == "DESC") ? 'CHECKED' : ''); ?>>
                <label for="decroissant">décroissant</label>
            </div>
        </div>	
        <div class="col_d">
            <label>Rechercher dans le forum</label>
            <select id="select_forum" name="select_forum" class="classic ombre">
                <option value="0">- Tous les forums -</option>
                <?php
                $requete_categories = "SELECT * FROM forum_categories ORDER by cat_order ASC";
                $res_categories = mysqli_query_with_error($mysqli, $requete_categories);
                while ($ligne = $res_categories->fetch_assoc()) {
                    echo '<optgroup label="' . get_data_propre_sortie_db($ligne['cat_title']) . '">';
                    $requete_forum = "SELECT * FROM forums WHERE cat_id=" . $ligne['cat_id'];
                    $res_forums = mysqli_query_with_error($mysqli, $requete_forum);
                    while ($forum = $res_forums->fetch_array()) {
                        echo '<option value="' . $forum['forum_id'] . '" ' . (($cherche_forum == $forum['forum_id']) ? 'SELECTED' : '') . '>' . get_data_propre_sortie_db($forum['forum_name']) . '</option>';
                    }
                    echo '</optgroup>';
                }
                ?>
            </select>


            <input class="btn ombre" type="submit" name="btn_recherche" value="Rechercher">

        </div>        

    </form>
    <div id="recherche_resultat">

        <h5>Résultats de la recherche</h5>

        <div class="col_g">
            <p class="resultat"><?php echo $feedback ?></p>
        </div>	

        <div class="col_d">

        </div>
    </div>
    <?php
    if ($from != "" && $nb_message>0) {
        switch ($type_recherche) {
            case 'topics':
                ?>
                <ul id="entete_forum">
                    <li class="sujet"><span>Sujet</span></li>
                    <li class="reponses milieu">Réponses</li>
                    <li class="auteur milieu">Auteur</li>
                    <li class="vues milieu">Vues</li>
                    <li class="msg"><span>Derniers messages</span></li>
                </ul>
                <?php
                $bordure = "";
                $result = mysqli_query_with_error($mysqli, "SELECT * " . $from . ' ' . $limit);
                while ($topic = $result->fetch_array()) {

                    if (get_data_in_db($mysqli, "forums", "forum_id", $topic['forum_id'], "auth_view") == '2' && @$_SESSION['grad'] != "admin") {
                        $result_perm = mysqli_query_with_error($mysqli, "SELECT forum_id FROM forum_private WHERE forum_id ='{$topic['forum_id']}' AND user_id='{$_SESSION['id']}' LIMIT 1");
                        if ($result_perm->num_rows == 0) {
                            continue;
                        }
                    }

                    // var_dump($ligne);
                    $idt = $topic['topic_id'];
                    if ($topic['topic_type'] == 1) {
                        $icone = "important";
                    } else {
                        $icone = "lu";
                    }
                    if (isset($_SESSION['new_topics']) && isset($_SESSION['new_topics']['topic_' . $topic['topic_id']])) {
                        if ($topic['topic_type'] == 1) {
                            $icone = "nonlu-important";
                        } else {
                            $icone = "nonlu";
                        }
                    }

                    if ($topic['topic_status'] == '1') {
                        $icone = "verrouille";
                    }
                    $is_deplac = "";
                    if ($topic['topic_moved_id'] != '0') {
                        $topic = get_line_in_db($mysqli, "forum_topics", "topic_id", $ligne['topic_moved_id']);
                        $is_deplac = "[Déplacé] ";
                    }
                    if ($topic['topic_sondage'] != "") {
                        $is_deplac = $is_deplac . "[Sondage] ";
                    }

                    $autor = "<a href='/perso/profil.php?id=" . $topic['topic_poster'] . "'  class='auteur'>" . get_data_in_db($mysqli, "gens", "user_id", $topic['topic_poster'], "username") . "</a>";
                    ?>

                    <div class="ligne <?php echo "$icone $bordure"; ?>">
                        <div class="sujet">
                            <?php
                            $titre = $is_deplac . get_data_propre_sortie_db($topic['topic_title']);
                            if ($motscle != "") {
                                for ($i = 0; $i < sizeof($tmots); $i++) {
                                    $titre = str_ireplace($tmots[$i], "<span class=\"motscles\">{$tmots[$i]}</span>", $titre);
                                }
                            }
                            ?>
                            <h5><a href="topic.php?id=<?php echo get_data_propre_sortie_db($topic['topic_id']); ?>"><?php echo $titre ?></a></h5>
                            <p class="description"><?php echo get_data_propre_sortie_db($topic['topic_sub_title']); ?></p>
                            <?php
                            //Pagination topic
                            $nb_post_par_page = 10;
                            $retour_total = mysqli_query_with_error($mysqli, "SELECT COUNT(*) AS total FROM forum_posts WHERE topic_id=" . $topic['topic_id']);
                            $donnees_total = $retour_total->fetch_assoc();
                            $total = $donnees_total['total'];

                            $nombreDePages = ceil($total / $nb_post_par_page);
                            $max_display = 4; //on affiche maximum 4 liens vers les pages
                            switch ($nombreDePages) {
                                case ($nombreDePages == 1):
                                    break;
                                case ($nombreDePages <= $max_display):
                                    echo '<p class="numero">Aller à la page : ';
                                    for ($i = 1; $i <= $nombreDePages; $i++) {
                                        echo '<a href="topic.php?id=' . $topic['topic_id'] . '&page=' . $i . '">' . $i . '</a>';
                                        if ($i < $nombreDePages) {
                                            echo ', ';
                                        }
                                    }
                                    break;
                                default :
                                    echo '<p class="numero">Aller à la page : ';
                                    echo '<a href="topic.php?id=' . $topic['topic_id'] . '&page=1">1</a>, ';
                                    echo '<a href="topic.php?id=' . $topic['topic_id'] . '&page=2">2</a>, ';
                                    echo '... , ';
                                    echo '<a href="topic.php?id=' . $topic['topic_id'] . '&page=' . ($nombreDePages - 1) . '">' . ($nombreDePages - 1) . '</a>, ';
                                    echo '<a href="topic.php?id=' . $topic['topic_id'] . '&page=' . ($nombreDePages) . '">' . ($nombreDePages) . '</a>';
                                    break;
                            }
                            ?>

                        </div>
                        <div class="reponses milieu">
                            <?php
                            $query = "SELECT COUNT(*) FROM forum_posts WHERE topic_id=" . $idt;
                            list($nb_post) = mysqli_query_with_error($mysqli, $query)->fetch_array();
                            ?>
                            <p><?php echo ($nb_post - 1); ?></p>
                        </div>
                        <div class="auteur milieu">
                            <p><?php echo $autor ?></p>
                        </div>
                        <div class="vues milieu">
                            <p><?php echo $topic['topic_views'] ?></p>
                        </div>
                        <div class="msg">
                            <p class="description">
                                <?php
                                $dpost = mysqli_query_with_error($mysqli, "SELECT * FROM forum_posts WHERE topic_id = " . $idt . " ORDER BY post_time DESC LIMIT 1")->fetch_assoc();
                                $datp = datouille($dpost['post_time'], true);
                                $autor = $dpost['post_username'];
                                if ($dpost['poster_id'] != "0") {
                                    $autor = get_data_in_db($mysqli, "gens", "user_id", $dpost['poster_id'], "username");
                                    ?>
                                    par <a href="/perso/profil.php?id=<?php echo $dpost['poster_id'] ?>" class="auteur"><?php echo get_data_propre_sortie_db($autor) ?></a> <a href="topic.php?id=<?php echo $topic['topic_id'] ?>&page=<?php echo $nombreDePages ?>#<?php echo $dpost['post_id'] ?>" class="fleche"></a><br/>
                                    <span class="date"><?php echo $datp ?></span>
                                    <?php
                                }
                                ?>
                            </p>
                        </div>
                    </div>
                    <?php
                    $bordure = "bordure";
                }

                break;
            case 'posts':
                $result = mysqli_query_with_error($mysqli, "SELECT * " . $from . ' ' . $limit);
               
                    
                    $nb_current = display_posts($mysqli, $result, 0, $pageActuelle, $motscle);

                    
                    
               
                break;
        }
    }
    ?>

</div>

<?php
if ($type_recherche!='topics' && $from != "" && $nb_message>0) {
pagination_bas('recherche.php?'.$get, '&page=', $nombreDePages, $page);
}

?>


    </div>
</div>

<?php
show_footer();
